package com.ikdong.toodle.util;

import java.util.List;

import android.content.Context;
import android.util.Log;

import com.ikdong.toodle.dao.AccountDAO;
import com.ikdong.toodle.model.Account;

public class AccountManager {
	private AccountDAO dao;
	private AuthManager authManager;
	
	public AccountManager(Context context){
		dao = new AccountDAO(context);
		authManager = new AuthManager(context);
	}
	
	public boolean add(Account account){
		return dao.add(account);
	}
	
	public boolean add(String json){
		Account account = JsonUtil.parseToAccount(json);
		return dao.add(account);
	}
	
	public boolean save(Account account){
		boolean flag = false;
		dao.delete();
		flag = dao.add(account);
		return flag;
	}
	
	public boolean update(String key){
		Log.d(Constant.TAG, "Start to update Account......");
		boolean flag = false;
		try{
			Account account = ToodleHttpClient.lookupAccount(key);
			Log.d(Constant.TAG, "Account: "+account);
			if(account!=null){
				account.setLastedit_folder(Long.valueOf(0));
				account.setLastedit_task(Long.valueOf(0));
				flag = save(account);
			}
		}catch(Exception e){
			Log.e(Constant.TAG, "AccountManager.update() error", e);
		}
		return flag;
	}
	
	public Account getAccount(){
		Account account = null;
		List<Account> accounts = dao.get();
		if(accounts.size()>0){
			account = accounts.get(0);
		}
		return account;
	}
	
	public void logout(){
		dao.delete();
		authManager.delete();
	}
	
	public Account getAccountFromServer(){
		Account account = null;
		String key = authManager.getKey();
		if(key!=null){
			account = ToodleHttpClient.lookupAccount(key);
		}
		return account;
	}
}
